package com.bootdo.clouddo.service.sms.impl;

import com.alibaba.fastjson.JSON;
import com.bootdo.clouddo.dao.sys.SysSmsLogMapper;
import com.bootdo.clouddo.domain.sys.SysSmsLog;
import com.bootdo.clouddo.utils.common.CommonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;

/**
 * 发送短信服务类
 * @author WD
 *
 */
@Service
public class SysSMSSenderService {
	
	public static final Logger logger = LoggerFactory.getLogger(SysSMSSenderService.class);
	
	@Autowired
	private AliSMSenderService sMSSenderService;
	
	@Autowired
	private MessageSource messageSource;
	
	@Autowired
	private SysSmsLogMapper sysSMSDao;
	
	public void doSendSMS(String mobile,final String code, final String type) throws Exception {
		if(!CommonUtils.matchMobile(mobile)){
			throw new Exception("mobile_invalid");
		}
		//根据操作类型获取短信模板
		String templateCode = messageSource.getMessage(type, null, null);
		
		long startTime = System.currentTimeMillis();
		logger.debug("send message start............code:" + code);
		
		sendSMS(mobile, templateCode, "{\"code\": \""+ code +"\"}", type);
		
		logger.debug("send message end..........");
		logger.debug("send time :"+(System.currentTimeMillis()-startTime)+"ms");
	}
	
	/**
	 * 
	 * @param mobile
	 * 			短信内容
	 * @param msgType
	 * 			短信类型
	 * @return
	 * 			返回smslog的ID
	 * @throws Exception 
	 */
	public String sendSMS(String mobile, String templateCode, String templateParam, String msgType) throws Exception{
		String rslt = sMSSenderService.sendSms(mobile, templateCode, templateParam);
		SysSmsLog smsLog = new SysSmsLog();
		Map<String, String> content = new HashMap<>();
		content.put("templateCode", templateCode);
		content.put("templateParam", templateParam);
		smsLog.setContent(JSON.toJSONString(content));
		smsLog.setStatusMsg(rslt);
		smsLog.setSendTime(new Timestamp(System.currentTimeMillis()));
		smsLog.setType(msgType);
		smsLog.setMobile(mobile);
		return String.valueOf(sysSMSDao.insertSelective(smsLog));
	}
	
}
